package net.miranti;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.name.Names;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;

public class DevGuiceConfig extends GuiceServletContextListener {
	private static final Long msPerDay = new Long(24 * 60 * 60 * 1000);

	private Injector injector;
	
	@Override
	protected synchronized final Injector getInjector() {
		if (injector==null) {
			ServletModule servletConfig = new ServletModule() {
				@Override
				protected void configureServlets() {
					serve("*.rpc").with(GuiceRemoteServiceServlet.class);
				}
			};
			AbstractModule constantsConfig = new AbstractModule() {
				@Override
				protected void configure() {
					bind(Long.class).annotatedWith(Names.named("msPerDay")).toInstance(msPerDay);
				}
			};
			injector = Guice.createInjector(getAppModules(servletConfig, constantsConfig));
		}
		return injector;
	}
	
	private AbstractModule[] getAppModules(AbstractModule... modules) {
		List<AbstractModule> m = new LinkedList(Arrays.asList(modules));
		m.addAll(Arrays.asList(getAppModules()));
		return m.toArray(new AbstractModule[m.size()]);
	}

	protected AbstractModule[] getAppModules() {
		return new AbstractModule[0];
	}
}
